// @ts-expect-error - Howl类型声明问题
import { Howl } from "../lib/howler-wrapper.js";
import { useState, useRef, useEffect, forwardRef, useImperativeHandle } from "react";

export const HawlAudio = forwardRef<{ destroy: () => void }, { onDestroy?: () => void }>(({ onDestroy }, ref) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [volume, setVolume] = useState(0.5);
  const [isLoop, setIsLoop] = useState(true);
  const howlRef = useRef<Howl | null>(null);

  useImperativeHandle(ref, () => ({
    destroy: () => {
      if (howlRef.current) {
        console.log('🧹 手动销毁Howl实例');
        howlRef.current.stop();
        howlRef.current.unload();
        onDestroy?.();
      }
    }
  }));

  useEffect(() => {
    console.log('🔧 初始化Howl实例, loop:', isLoop);
    
    // 检测iOS设备
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
    const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
    console.log('📱 设备检测 - iOS:', isIOS);
    console.log('📱 iOS版本:', iosVersion || '未知');
    console.log('📱 User Agent:', navigator.userAgent);
    console.log('📱 Web Audio支持:', typeof AudioContext !== 'undefined' || typeof (window as unknown as {webkitAudioContext?: unknown}).webkitAudioContext !== 'undefined');
    
    // 初始化Howl实例
    howlRef.current = new Howl({
      src: ['https://creation.codemao.cn/884/l31cw9bi.mpeg'],
      volume: volume,
      loop: isLoop,
      html5: false,
      onplay: (id: number) => {
          console.log('▶️ onplay 触发, soundId:', id);
          console.log('🔍 当前loop状态:', howlRef.current?.loop());
          console.log('🔍 当前HTML5模式:', howlRef.current?._html5);
          console.log('🔍 Web Audio模式:', howlRef.current?._webAudio);
          // console.log('Howler Node:', howlRef.current);
          // console.log('🔍 全局Howler AudioContext:', (window as unknown as {Howler?: {ctx?: unknown}}).Howler?.ctx || 'undefined');
          // console.log('🔍 全局Howler masterGain:', (window as unknown as {Howler?: {masterGain?: unknown}}).Howler?.masterGain || 'undefined');
          // console.log('🔍 全局Howler usingWebAudio:', (window as unknown as {Howler?: {usingWebAudio?: boolean}}).Howler?.usingWebAudio);
          setIsPlaying(true);
      },
      onpause: (id: number) => {
          console.log('⏸️ onpause 触发, soundId:', id);
          setIsPlaying(false)
      },
      onstop: (id: number) => {
          console.log('⏹️ onstop 触发, soundId:', id);
          setIsPlaying(false)
      },
      onend: (id: number) => {
          console.log('🏁 onend 触发, soundId:', id);
          console.log('🔍 当前loop状态:', howlRef.current?.loop());
          
          const sound = howlRef.current?._sounds?.[0];
          const node = sound?._node;
          
          if (howlRef.current?._webAudio) {
            // Web Audio模式下的属性
            console.log('🔍 Web Audio节点类型:', node?.constructor?.name);
            console.log('🔍 Web Audio节点:', node);
            console.log('🔍 bufferSource:', node?.bufferSource);
            console.log('🔍 gain节点:', node?.gain);
            console.log('🔍 音频时长:', howlRef.current?.duration());
            console.log('🔍 当前播放时间:', sound?._seek || 0);
          } else {
            // HTML5 Audio模式下的属性
            console.log('🔍 HTML5节点loop属性:', node?.loop);
            console.log('🔍 HTML5节点currentTime:', node?.currentTime);
            console.log('🔍 HTML5节点ended属性:', node?.ended);
            console.log('🔍 HTML5节点duration:', node?.duration);
          }
          
          setIsPlaying(false);
      },
      onload: () => {
          console.log('📥 onload 触发 - 音频加载完成');
          console.log('🔍 音频时长:', howlRef.current?.duration());
          console.log('🔍 音频状态:', howlRef.current?.state());
      },
      onloaderror: (_: unknown, error: unknown) => {
        console.error('❌ 音频加载失败:', error);
        alert('音频文件加载失败，请检查网络连接');
      }
    });

    return () => {
      if (howlRef.current) {
        console.log('🧹 清理Howl实例');
        howlRef.current.stop();
        howlRef.current.unload();
        onDestroy?.();
      }
    };
  }, []);

  useEffect(() => {
    if (howlRef.current) {
      howlRef.current.volume(volume);
    }
  }, [volume]);

  const togglePlay = () => {
    if (!howlRef.current) {
      console.log('❌ Howl实例不存在');
      return;
    }
    if (isPlaying) {
      console.log('⏸️ 执行暂停操作');
      howlRef.current.pause();
    } else {
      console.log('▶️ 执行播放操作');
      const soundId = howlRef.current.play();
      console.log('🔍 播放返回的soundId:', soundId);
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    setVolume(newVolume);
  };

  const handleLoopToggle = () => {
    const newLoopState = !isLoop;
    console.log('🔄 切换循环状态:', isLoop, '->', newLoopState);
    setIsLoop(newLoopState);
    
    // 如果音频正在播放，立即更新循环状态
    if (howlRef.current && isPlaying) {
      console.log('🔍 音频正在播放，立即更新循环状态');
      howlRef.current.loop(newLoopState);
      console.log('🔍 更新后的循环状态:', howlRef.current.loop());
    }
  };


  return (
    <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto' }}>
      <h2>音频播放器</h2>
      
      {/* 播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <button
          onClick={togglePlay}
          style={{
            padding: '10px 20px',
            fontSize: '16px',
            backgroundColor: isPlaying ? '#ff4444' : '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            marginRight: '10px'
          }}
        >
          {isPlaying ? '停止' : '播放'}
        </button>
        <button
          onClick={() => {
            if (howlRef.current) {
              const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
              const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
              console.log('🔍 手动检查音频状态:');
              console.log('  - 播放状态:', howlRef.current.playing());
              console.log('  - 循环状态:', howlRef.current.loop());
              console.log('  - 音频状态:', howlRef.current.state());
              console.log('  - HTML5模式:', howlRef.current._html5);
              console.log('  - Web Audio模式:', howlRef.current._webAudio);
              console.log('  - iOS版本:', iosVersion || '未知');
              console.log('  - User Agent:', navigator.userAgent);
              console.log('  - 全局AudioContext状态:', (window as unknown as {Howler?: {ctx?: {state?: string}}}).Howler?.ctx?.state);
              console.log('  - 全局AudioContext:', (window as unknown as {Howler?: {ctx?: unknown}}).Howler?.ctx);
              console.log('  - 全局masterGain:', (window as unknown as {Howler?: {masterGain?: unknown}}).Howler?.masterGain);
              console.log('  - 全局usingWebAudio:', (window as unknown as {Howler?: {usingWebAudio?: boolean}}).Howler?.usingWebAudio);
              console.log('  - 音频节点:', howlRef.current._sounds?.[0]?._node);
              if (howlRef.current._sounds?.[0]?._node) {
                const node = howlRef.current._sounds[0]._node;
                const sound = howlRef.current._sounds[0];
                
                if (howlRef.current._webAudio) {
                  // Web Audio模式
                  console.log('  - Web Audio节点类型:', node.constructor?.name);
                  console.log('  - bufferSource:', node.bufferSource);
                  console.log('  - gain节点:', node.gain);
                  console.log('  - 当前播放时间:', sound._seek || 0);
                  console.log('  - 播放速率:', sound._rate || 1);
                  console.log('  - 节点音量:', sound._volume || 1);
                  console.log('  - 节点静音:', sound._muted || false);
                } else {
                  // HTML5 Audio模式
                  console.log('  - 节点循环:', node.loop);
                  console.log('  - 节点结束:', node.ended);
                  console.log('  - 当前时间:', node.currentTime);
                  console.log('  - 音频时长:', node.duration);
                  console.log('  - 播放速率:', node.playbackRate);
                  console.log('  - 节点音量:', node.volume);
                  console.log('  - 节点静音:', node.muted);
                }
              }
            }
          }}
          style={{
            padding: '10px 20px',
            fontSize: '14px',
            backgroundColor: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer'
          }}
        >
          调试信息
        </button>
      </div>

      {/* 音量控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'block', marginBottom: '10px' }}>
          音量: {Math.round(volume * 100)}%
        </label>
        <input
          type="range"
          min="0"
          max="1"
          step="0.1"
          value={volume}
          onChange={handleVolumeChange}
          style={{ width: '100%' }}
        />
      </div>

      {/* 循环播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <input
            type="checkbox"
            checked={isLoop}
            onChange={handleLoopToggle}
            style={{ transform: 'scale(1.2)' }}
          />
          <span>循环播放</span>
        </label>
      </div>

      {/* 状态显示区域 */}
      <div style={{ fontSize: '14px', color: '#666', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '5px' }}>
        <p>状态: {isPlaying ? '播放中' : '已停止'}</p>
        <p>音量: {Math.round(volume * 100)}%</p>
        <p>循环播放: {isLoop ? '开启' : '关闭'}</p>
        <p>设备: {(() => {
          const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
          if (isIOS) {
            const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
            const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
            return `iOS ${iosVersion || '未知版本'}`;
          }
          return '非iOS';
        })()}</p>
        {howlRef.current && (
          <>
            <p>音频状态: {howlRef.current.state()}</p>
            <p>实际循环状态: {howlRef.current.loop() ? '开启' : '关闭'}</p>
            <p>HTML5模式: {howlRef.current._html5 ? '是' : '否'}</p>
            <p>Web Audio模式: {howlRef.current._webAudio ? '是' : '否'}</p>
            <p>AudioContext状态: {(window as unknown as {Howler?: {ctx?: {state?: string}}}).Howler?.ctx?.state || '未知'}</p>
            <p>音频时长: {howlRef.current.duration() ? howlRef.current.duration().toFixed(2) + 's' : '未知'}</p>
            {howlRef.current._sounds?.[0]?._node && (
              <>
                {howlRef.current._webAudio ? (
                  <>
                    <p>Web Audio节点: {howlRef.current._sounds[0]._node.constructor?.name || '未知'}</p>
                    <p>当前播放时间: {(howlRef.current._sounds[0]._seek || 0).toFixed(2)}s</p>
                    <p>播放速率: {howlRef.current._sounds[0]._rate || 1}</p>
                    <p>节点音量: {howlRef.current._sounds[0]._volume || 1}</p>
                  </>
                ) : (
                  <>
                    <p>节点循环: {howlRef.current._sounds[0]._node.loop ? '开启' : '关闭'}</p>
                    <p>节点结束: {howlRef.current._sounds[0]._node.ended ? '是' : '否'}</p>
                    <p>当前时间: {howlRef.current._sounds[0]._node.currentTime ? howlRef.current._sounds[0]._node.currentTime.toFixed(2) + 's' : '0s'}</p>
                  </>
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
});